package com.rtsapp.server.logger.appender;

import com.rtsapp.server.logger.async.IAsyncLogger;
import com.rtsapp.server.logger.spi.LogLevel;
import com.rtsapp.server.logger.spi.LogLog;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 异步日志类
 * 1. AsyncLoggerAppender 必须是线程安全的
 * 2. 支持多生产者，单消费者就行
 */
public class AsyncLoggerAppender<T> implements ILoggerAppender<T> , IAsyncLogger {

    private static final int MAX_LOG_QUEUE_SIZE = 10000000;

    /**
     * 用于接收日志的队列, ArrayBlockingQueue 性能较高, 实际使用看看
     */
//    private final LockfreeLinkedQueue queue = new LockfreeLinkedQueue();
    private final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>( MAX_LOG_QUEUE_SIZE );

    /**
     * 需要输出到的日志文件
     */
    private final ILoggerAppender<T> appender;


    public AsyncLoggerAppender(  ILoggerAppender<T> logger) {
        this.appender = logger;
    }


    @Override
    public void appendLog(T log) {
        try {
            queue.put(log);
        } catch (InterruptedException e) {
            LogLog.error( "日志队列满,被中断" , e );
        }
    }


    public long doLogger() throws InterruptedException {

        long size = queue.size();
        if( size > 0   ){
            for( int i = 0; i < size; i++ ){
                T log = queue.take();
                if( log != null ){
                    appender.appendLog(log);
                }
            }
        }

        return size;
    }

    @Override
    public void close() {
        appender.close();
    }


}
